#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <stdio.h>
#include <string.h>
#include <QFileDialog>
#include <QStandardItemModel>
#include <QStandardItem>
#include <QItemSelectionModel>
#include <QDebug>
#include "glrenderer.h"
#include "ammmanager.h"
#include "amentitymanager.h"
#include "base/amscene.h"

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);   
    m_LightDialog = new LightDialog(this);
    m_MeshDataDialog = new MeshDataDialog(this);
    m_TransformationDialog = new TransformationDialog(this);

    m_GLRenderer = new GLRenderer;
    m_SceneListModel = new SceneListModel;

    m_Filename = "";
    m_EntityName = "";

    ui->sceneGraph->setModel(m_SceneListModel->getItemModel());

    connect(ui->actionOpen_OBJ, SIGNAL(triggered()), SLOT(dialogOpenOBJ()));
    connect(ui->actionExport_AM, SIGNAL(triggered()), SLOT(dialogExportAM()));

    connect(ui->actionShow_LightsDialog, SIGNAL(triggered()),
            m_LightDialog, SLOT(show()));
    connect(ui->actionShow_DataDialog, SIGNAL(triggered()),
            m_MeshDataDialog, SLOT(show()));
    connect(ui->actionAdjust_Transformations, SIGNAL(triggered()),
            m_TransformationDialog, SLOT(show()));

    connect(ui->sceneGraph->selectionModel(),
            SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)),
            SLOT(selectionChanged(const QItemSelection &, const QItemSelection &)));

    ui->horizontalLayout->addWidget(m_GLRenderer);
}

MainWindow::~MainWindow()
{
    delete ui;
    delete m_SceneListModel;
    delete m_GLRenderer;
}

void MainWindow::addModel(const QString & modelName, MeshData*)
{
    m_SceneListModel->addItem(modelName);
}

void MainWindow::dialogOpenOBJ()
{
    m_Filename = QFileDialog::getOpenFileName(this, tr("Open File"), tr(""), tr("*.obj"));
    emit(openOBJ(m_Filename));
}

void MainWindow::dialogExportAM()
{    
    m_Filename = QFileDialog::getSaveFileName(this, tr("Export Model"), tr(""), tr("*.am"));
    emit(exportAM(m_EntityName, m_Filename));
}

void MainWindow::selectionChanged(const QItemSelection & , const QItemSelection & )
{
    const QModelIndex index = ui->sceneGraph->selectionModel()->currentIndex();
    m_EntityName = index.data(Qt::DisplayRole).toString();
    AMScene::get()->clear();
    AMVirtualEntity * e = AMEntityManager::get()->fetch(m_EntityName);
    if(e != NULL) {
        AMScene::get()->add(e);
        qDebug() << m_EntityName;
    }
}
